﻿using UnityEngine;
using System.Collections;
using System.Xml;
using System.Collections.Generic;
using Clojure;
public class Actor
{
    public string PrefabPath;
    Context Context; 
    public Vector3 Scale;
    public Vector3 Offset;
    public Unit mUnit;
    Dictionary<string, List<ASTNode>> Events = new Dictionary<string,List<ASTNode>>();

    public GameObject ActorGameObject;

    public Actor() { }
    public Actor(Unit unit,XmlActor actor) 
    {
        this.PrefabPath = actor.PrefabPath;
        this.mUnit = unit;
        this.Scale = actor.Scale;
        this.Offset = actor.Offset;

        Context = new Clojure.Context(unit.Context);
        this.DefineActorFuncs();

        ASTTree tree = ASTTree.ParseString(actor.Name+mUnit.Id,actor.EventScript);
        RT.EvaluateTree(tree,this.Context);
    }
    public void Init() 
    {
        GameObject ActorPrefab = (GameObject)Resources.Load(this.PrefabPath);
        if (this.ActorGameObject == null)
        {
            this.ActorGameObject = (GameObject)GameObject.Instantiate(ActorPrefab);
            this.ActorGameObject.transform.parent = mUnit.transform;
            this.ActorGameObject.transform.localScale = Vector3.Scale(ActorPrefab.transform.localScale, this.Scale);
            this.ActorGameObject.transform.localPosition = Vector3.zero + this.Offset;
            this.ActorGameObject.transform.localRotation = Quaternion.identity;
        }
        else 
        {
            this.ActorGameObject.SetActive(true);
        }
    }

    public void DefineActorFuncs() 
    {
        this.Context.Define("self-actor",new ObjectNode(this));
    }

    public void CallEvent(string eventName)
    {
        List<ASTNode> lstNode = this.Events[eventName];
        for (int i = 0; i < lstNode.Count;i++ )
        {
            RT.Evaluate(lstNode[i], this.Context);
        }
        
    }

    public void AddEvent(string eventName,ASTNode node)
    {
        if (!this.Events.ContainsKey(eventName))
        {
            this.Events[eventName] = new List<ASTNode>();
        }
        this.Events[eventName].Add(node);
    }
   
}


public class XmlActor 
{
    public string EventScript; 
    public string Name;
    public string PrefabPath;
    public Vector3 Scale = Vector3.one;
    public Vector3 Offset;
    public void parse(XmlNode node) 
    {
        this.Name = node.Attributes["Name"].Value;
        this.PrefabPath = node.Attributes["PrefabPath"].Value;
        XmlNode eventNode = node.SelectSingleNode("UnitEvents");
        if (node.Attributes["Scale"] != null) 
        {
            this.Scale = SGTools.ParseV3(node.Attributes["Scale"].Value);
        }
        if (node.Attributes["Offset"] != null) 
        {
            this.Offset = SGTools.ParseV3(node.Attributes["Offset"].Value);
        }
        if (eventNode != null)
        {
            this.EventScript = eventNode.InnerText;
        }
    }
}